import lombok.extern.slf4j.Slf4j;

/**
 * @author 管子
 * @date 2025/4/26 12:46
 * @description: TestDoubleCheckLock 类
 */
@Slf4j
public class TestDoubleCheckLock {

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                Singleton instance = Singleton.getInstance();
                log.info("{}", instance);
            }, "t" + i).start();
        }
        Thread.sleep(10000);
    }

}

// 双重检测锁 单例
final class Singleton {
    private Singleton() {}
    private volatile static Singleton INSTANLE = null;
    public static Singleton getInstance() {
        // 有序性，导致INSTANCE正在被锁里面的线程创建时且还没创建完成，外面的线程就判断存在了
        // 就会导致外面的线程拿着还没创建好的线程就出去使用了
        if (INSTANLE == null) {
            synchronized (Singleton.class) {
                if (INSTANLE == null) {
                    INSTANLE = new Singleton();
                }
            }
        }
        return INSTANLE;
    }

}
